package com.c6906.vdam.dcs.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;

/**
 * SM4 工具类
 */
public class SM4Utils {
    private static final String ALGORITHM_NAME = "SM4";
    private static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS7Padding";

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * SM4 加密 (ECB 模式)
     *
     * @param key       密钥字符串
     * @param plaintext 明文数据
     * @return 加密后的数据
     */
    public static byte[] encrypt(byte[] key, byte[] plaintext) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING, "BC");
        SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(plaintext);
    }

    /**
     * SM4 解密 (ECB 模式)
     *
     * @param key        密钥字符串
     * @param ciphertext 密文数据
     * @return 解密后的数据
     */
    public static byte[] decrypt(byte[] key, byte[] ciphertext) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING, "BC");
        SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return cipher.doFinal(ciphertext);
    }
}
